package com.hzhh123.channel;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

import org.junit.Test;
/**
 * 管道读写数据
 * @author hzhh123
 * @Date 2019年2月27日 下午3:42:13
 */
public class TestPipe {

	@Test
	public void test1() throws IOException {
		//获取管道
		Pipe pipe=Pipe.open();
		//写数据
		SinkChannel sinkChannel=pipe.sink();
		ByteBuffer buf=ByteBuffer.allocate(1024);
		buf.clear();
		buf.put("测试管道".getBytes());
		buf.flip();
		sinkChannel.write(buf);
		
		//读取管道中的数据
		SourceChannel sourceChannel=pipe.source();
		buf.flip();
		int len = sourceChannel.read(buf);
		System.out.println(new String(buf.array(),0,len));
		sinkChannel.close();
		sourceChannel.close();
	}
}
